package com.zyg.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import com.alibaba.fastjson2.JSON;
import com.zyg.pojo.User;
import com.zyg.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class LoginController {
    @Autowired
    private UserService userService;

    @RequestMapping()
    public String tologin(){
        return "login";
    }
    @RequestMapping("/login")
    public String login(User user, String code, HttpSession session){
        //校验验证码
        String sessionCode = (String) session.getAttribute("code");
        if(!sessionCode.equalsIgnoreCase(code)){
            return "redirect:/";
        }else{
            User u = userService.login(user);
            if(u !=null){
                //重启用户登陆凭证
                StpUtil.login(u.getId());
              // return "index";
               return "redirect:/toindex";
            }else{
                return "redirect:/";
            }
        }

    }
    @RequestMapping("/captcha")
    @ResponseBody
    public String captcha(HttpSession session){
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(250,100,4,4);
        String code = captcha.getCode();
       //将验证码存入session
        session.setAttribute("code",code);
        String data= JSON.toJSONString(captcha.getImageBase64());
        return data;
    }
}
